<?php
namespace app\service;

use app\model\DistributionOfficerLogModel;
use app\model\DistributionOfficerModel;
use app\model\GoodsConcernModel;
use app\model\MemberModel;
use app\model\MembersRelationModel;
use app\model\MemberThirdOauthModel;
use app\model\OrderDistributionModel;
use app\model\OrderModel;
use support\Db;
use support\facade\Logger;
use const support\CORRECT;
use const support\customer_service_contact_mobile;
use const support\customer_service_wechat_account;
use const support\DENY;
use const support\OPERATE_ERROR;
use const support\order_status_0;
use const support\order_status_1;
use const support\order_status_8;
use const support\PARAMETER_ERROR;

class MemberService
{

    //第三方登录/注册
    public static function thirdLoginOrRegister(int $thirdType,string $thirdOpenid,int $pid,string $nickname='',string $avatar=''){
        try {
            //检测是否存在
            list($memberId,$memberThirdOauthId)=MemberThirdOauthModel::getMemberThirdOauthByOpenid($thirdType,$thirdOpenid);
            if (!is_numeric($memberId)){
                //不存在则创建
                $memberThirdOauthId=MemberThirdOauthModel::createMemberThirdOauth($thirdType,$thirdOpenid,$pid,$nickname,$avatar);
            }
            return [$memberId,$memberThirdOauthId];
        }catch (\Throwable $e){
            Logger::app($e);
            return false;
        }
    }

    //注册或登录操作
    public static function userLoginOrRegister(string $mobile,int $memberThirdOauthId=0,int $pid=0)
    {
        //查询用户是否存在
        $member=MemberModel::queryMemberByMobile($mobile);
        $memberId=$member['id']??0;
        Logger::app('注册或登录操作1','info',[$memberId]);
        Db::beginTransaction();
        try {
            if ($memberId){
                $ret=MemberModel::updateMemberLoginDataByMemberId($memberId);
                Logger::app('注册或登录操作2','info',[$ret]);
                if (!$ret){
                    Db::rollBack();
                    Logger::app('用户更新登录信息失败');
                    return false;
                }
            }else{
                $memberId=MemberModel::userRegister($mobile);
                Logger::app('注册或登录操作3','info',[$memberId]);
                if (!$memberId){
                    Db::rollBack();
                    Logger::app('用户注册信息失败');
                    return false;
                }
                //存在销售ID则关联绑定
                if ($pid){
                    $ret=MembersRelationModel::insertGetId([
                        'member_id'     =>$memberId,
                        'pid'           =>$pid,
                        'create_time'   =>time()
                    ]);
                    Logger::app('用户邀请数据绑定结果','info',[$ret]);
                }
            }
            Logger::app('注册或登录操作4','info',[$memberThirdOauthId]);
            //检测授权表中是否存在
            if (!empty($memberThirdOauthId)){
                $ret=MemberThirdOauthModel::toBindMemberThirdOauthRelation($memberThirdOauthId,$memberId);
                Logger::app('注册或登录操作5','info',[$ret]);
                if (!$ret){
                    Db::rollBack();
                    Logger::app('用户与三方授权信息表绑定失败');
                    return false;
                }
            }
            Db::commit();
            return $memberId;
        } catch (\Throwable $exception) {
            Db::rollBack();
            Logger::app($exception);
            return false;
        }
    }

    /**
     * 邀请数据
     * @param int $memberId
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function  memberRelations(int $memberId,int $page,int $limit): array
    {
        $totalNum=MembersRelationModel::where([
            'pid'=>$memberId,
            'status'=>CORRECT
        ])->count();
        $offset=($page-1)*$limit;
        $lists= MembersRelationModel::where([
            'pid'=>$memberId,
            'status'=>CORRECT
        ])->with([
            'members'=>function($query){
                $query->select(['id','mobile','nickname','avatar','create_time']);
            }
        ])->offset($offset)->limit($limit)->select(['member_id'])->get()->toArray();
        $memberIds=array_column($lists,'member_id');
        //获取每个邀请用户下单数量
        $orders=OrderModel::whereIn('member_id',$memberIds)->whereIn('order_status',[order_status_1,order_status_8])->select([
            'member_id',Db::raw('count(id) as order_num')
        ])->groupBy('member_id')->get()->toArray();
        $orderNums=array_column($orders,'order_num','member_id');
        $lists=array_map(function ($item)use($orderNums){
            //拼装整合数据
            return [
                'mobile'=>$item['members']['mobile']??'',
                'nickname'=>$item['members']['nickname']?:'微信用户',
                'avatar'=>$item['members']['avatar']?:sprintf("%s/image/default.png",env('APP_URL')),
                'create_time'=>$item['members']['create_time']??'',
                'order_num'=>$orderNums[$item['member_id']]??0
            ];
        },$lists);
        return commonPagingData($lists,$page,$limit,$totalNum);
    }

    //个人中心信息
    public static function getUserCenter(int $memberId): array
    {
        //定义个人中心返回数据
        $data=[
            'is_register'       =>DENY,
            'nickname'          =>'',
            'avatar'            =>sprintf("%s/image/default.png",env('APP_URL')),
            'goods_concern_num' =>0,
            'is_promotion'      =>DENY,
            'unpaid_order'      =>[],
            'customer_service'  =>[
                    'wechat_account'=>'',
                    'contact_mobile'=>''
            ],
            'about_user_url'    =>''
        ];
        //检测是否关联注册
        $data['is_register']=$memberId?CORRECT:DENY;
        if ($memberId){
            $member=MemberModel::where('id',$memberId)->where('status',CORRECT)->select(['id','nickname','avatar'])->first();
            if (!empty($member->id)){
                $data['nickname']=$member->nickname;
                $data['avatar']=$member->avatar?:$data['avatar'];
            }
            //检测是否存在未支付订单
            $order=OrderModel::where([
                'member_id'=>$memberId,
                'order_status'=>order_status_0,
                'status'=>CORRECT
            ])->select([
                'id','order_sn','goods_title','goods_num','goods_icon','order_actual_amount','goods_period_title','goods_icon'
            ])->orderBy('id','desc')->limit(1)->get()->toArray();
            $data['unpaid_order']=$order;
            //检测收藏数
            $data['goods_concern_num']=GoodsConcernModel::where([
                'member_id'=>$memberId,
                'status'=>CORRECT
            ])->count();
        }
        //获取客服和关于我们链接信息
        $data['customer_service']['wechat_account']=customer_service_wechat_account;
        $data['customer_service']['contact_mobile']=customer_service_contact_mobile;
        $data['about_user_url']=sprintf("%s",'667e1c89e864162ead0a8fa2');
        $isPromotion=MemberService::checkDistributionOfficerAuth($memberId);
        if ($isPromotion==DENY){
            $status=DistributionOfficerLogModel::where([
                'member_id'=>$memberId
            ])->orderBy('id','desc')->value('status');
            if ($status===0){
                $isPromotion=3;
            }
            if ($status==2){
                $isPromotion=4;
            }
        }
        $data['is_promotion']=$isPromotion;
        return $data;
    }

    //查询当前用户是否为分销官
    public static function checkDistributionOfficerAuth(int $memberId){
        return DistributionOfficerModel::where([
            'member_id'=>$memberId
        ])->where('status',1)->value('status')??DENY;
    }

    //申请开通分销系统
    public static function applyDistributionActivation(int $memberId,string $applyName,string $applyMobile): array
    {
        //查询当前用户是否已注册分销官
        $ret=MemberService::checkDistributionOfficerAuth($memberId);
        if ($ret==1){
            return formatReturnData(PARAMETER_ERROR,'该用户已成为推荐官，请勿重复申请');
        }
        //检测是否已提交审核请求
        $ret=DistributionOfficerLogModel::where([
            'member_id'=>$memberId,
            'status'   =>0
        ])->value('id')??0;
        if ($ret){
            return formatReturnData(PARAMETER_ERROR,'您的申请正在审核中，请及时关注');
        }
        $ret=DistributionOfficerLogModel::insertGetId([
            'member_id'=>$memberId,
            'real_name'=>$applyName,
            'mobile'   =>$applyMobile,
            'create_time'=>time()
        ]);
        if (!$ret){
            return formatReturnData(OPERATE_ERROR,'申请推荐官失败');
        }
        return formatReturnSuccessData();
    }

    //第三方头像昵称添加和修改
    public static function modifyNicknameAndAvatar(int $thirdOauthId,string $nickname,string $avatar){
        return MemberThirdOauthModel::where([
            'id'=>$thirdOauthId,
        ])->update([
            'third_nickname'=>$nickname,
            'third_avatar'  =>$avatar,
            'update_time'   =>time()
        ]);
    }

    //解除用户关系绑定
    public static function toUnbindRelationship($openid): bool
    {
        $info=MemberThirdOauthModel::where([
            'third_openid'=>$openid,
            'status'=>CORRECT
        ])->first();
        if (empty($info->id)){
            return false;
        }
        $info=$info->toArray();
        if ($info['member_id']){
            //清空用户头像昵称
            MemberModel::where([
                'id'=>$info['member_id']
            ])->update([
                'nickname'=>'',
                'avatar'=>'',
                'update_time'=>time()
            ]);
        }
        MemberThirdOauthModel::where([
            'id'=>$info['id']
        ])->update([
            'member_id'=>0,
            'third_nickname'=>'',
            'third_avatar'=>'',
            'update_time'=>time()
        ]);
        return true;
    }

    //检测用户是否具备分销权限
    public static function checkUserDistributionAuth(int $memberId): bool
    {
        return (bool)DistributionOfficerModel::where([
            'member_id'=>$memberId,
            'status'   =>CORRECT
        ])->value('id');
    }

}